#! /usr/bin/env python
# encoding: utf-8
# Richard Quirk, 2008

"""
Execute tests during the build - requires cppunit

To force all tests, run with "waf build --alltests"
"""

from waflib.Tools import waf_unit_test

top = '.'
out = 'build'

def options(opt):
	opt.load('compiler_cxx')
	opt.load('waf_unit_test')

def configure(conf):
	conf.load('compiler_cxx')
	conf.load('waf_unit_test')

	# the demo files require cppunit - but the waf tool does not
	conf.check_cfg(package='cppunit', args='--cflags --libs', mandatory=True)
	if 'dl' not in conf.env.LIB_CPPUNIT:
		l = conf.check(lib='dl', uselib_store='CPPUNIT')

	# the interpreted tests need python
	conf.find_program('python', mandatory=False)

from waflib import Logs
def summary(bld):
	lst = getattr(bld, 'utest_results', [])
	if lst:
		total = len(lst)
		tfail = len([x for x in lst if x[1]])

		val = 100 * (total - tfail) / (1.0 * total)
		Logs.pprint('CYAN', 'test report %3.0f%% success' % val)

		Logs.pprint('CYAN', '  tests that fail %d/%d' % (tfail, total))
		for (f, code, out, err) in lst:
			if code:
				Logs.pprint('CYAN', '    %s' % f)
				Logs.pprint('RED', 'status: %r' % code)
				if out: Logs.pprint('RED', 'out: %r' % out)
				if err: Logs.pprint('RED', 'err: %r' % err)

def build(bld):
	bld.recurse('src tests')

	# waf_unit_test.summary is a pretty ugly function for displaying a report (feel free to improve!)
	# results -> bld.utest_results [(filename, returncode, stdout, stderr), (..., ), ...]
	#bld.add_post_fun(waf_unit_test.summary)
	bld.add_post_fun(summary)

	# to execute all tests:
	# $ waf --alltests
	# to set this behaviour permanenly:
	#bld.options.all_tests = True
	bld.options.clear_failed_tests = True

	# debugging zone:
	# $ waf --zones=ut
	# setting the cwd for a unit test execution: see tests/test1/wscript_build (ut_cwd)

